package queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * ArrayBlockingQueue有界队列
 */
public class TestArrayBlockingQueue {

    public static void main(String[] args) {
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(3);
        Provider provider = new Provider(queue);
        Consumer consumer = new Consumer(queue);
        new Thread(provider).start();
        new Thread(consumer).start();
    }
}

class Provider implements Runnable{
    private BlockingQueue<String> queue;

    public Provider(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        System.out.println("所有人都来了");
        for (int i = 0; i < 10; i++) {
            String people = "people "+i;
            try {
                queue.put(people);
                System.out.println("候选人 " + people + " 安排好了");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 表示到了最后了
        try {
            queue.put("stop");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Consumer implements Runnable{

   private BlockingQueue<String> queue;

    public Consumer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String msg ;
        try {
            while (!(msg = queue.take()).equals("stop")){
                System.out.println("候选人" + msg + "到了");
            }
            System.out.println("所有人都结束了");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}